package com.bing.controller.comm;

import com.bing.services.impl.EnvServices;
import com.bing.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by kaibb on 2014/12/5.
 */
@Controller
@RequestMapping("util")
public class UtilsController implements InitializingBean {

    @Autowired
    private EnvServices envServices;
    private static Logger logger = LoggerFactory.getLogger(UtilsController.class);

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");


    @RequestMapping(value = "upload/{type}", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@PathVariable("type") String type, @RequestParam MultipartFile file) {
        return getPath(type, file);
    }

    private String getPath(String type, MultipartFile file) {
        File f = null;
        String fileName = null;
        try {
            String uploadDir = envServices.getUploadDir();
            ClassLoader cl = ClassUtils.getDefaultClassLoader();
            String path = cl.getResource("").getPath();
            f = new File(path + "../../" + uploadDir + type);
            fileName = sdf.format(new Date()) + file.getOriginalFilename();

            if (!f.exists()) {
                logger.info("初始化上传目录:{}", f.getAbsolutePath());
                f.mkdirs();
            }
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(f.getAbsolutePath() + "/" + fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/upload/" + type + "/" + fileName;
    }


    @RequestMapping(value = {"uploads/{type}/", "uploads/{type}"}, method = RequestMethod.POST)
    @ResponseBody
    public String upload(@PathVariable("type") String type, MultipartHttpServletRequest request) {
        MultiValueMap<String, MultipartFile> files = request.getMultiFileMap();
        List<String> paths = new ArrayList<>();
        for (String key : files.keySet()) {
            MultipartFile file = files.getFirst(key);
            paths.add(getPath(type, file));
        }

        return CommonUtils.GSON.toJson(paths.toArray());
    }

    @RequestMapping(value = "preview", method = RequestMethod.POST)
    @ResponseBody
    public String preview(@RequestParam("content") String content) {
        logger.info("预览markdown:{}", content);
        return content;
    }

    /**
     * 没有认证时跳转页面
     *
     * @return
     */
    @RequestMapping(value = "error/noAuth")
    @ResponseBody
    public String noAuth() {
        return "未登陆用户,请先登陆";
    }


    /**
     * Invoked by a BeanFactory after it has set all bean properties supplied
     * (and satisfied BeanFactoryAware and ApplicationContextAware).
     * <p>This method allows the bean instance to perform initialization only
     * possible when all bean properties have been set and to throw an
     * exception in the event of misconfiguration.
     *
     * @throws Exception in the event of misconfiguration (such
     *                   as failure to set an essential property) or if initialization fails.
     */
    @Override
    public void afterPropertiesSet() throws Exception {

    }
}

